<?php

namespace Admin\Frontend\Controllers;

use Helpers\Tool;
use Helpers\Main;
use Helpers\Template;
use Helpers\Assets;
use Helpers\UserPower;
use Helpers\TransitClient;
use CFPropertyList\CFPropertyList;
use Admin\Models\app\XhappStore;
use Admin\Models\app\XhappDroidwall;
use Admin\Models\app\XhappRetain;
use Admin\Models\res\XhresQuestionbankcontact;
class AppController extends ControllerBase
{


    /**
     * 应用列表页面
     * 根据模板文件，列表配置文件，用户权限显示内容
     *
     * create by ck 20160304
     * modify by ck 20160415    错误信息使用弹窗提示
     * modify by ck 20160616
     * modify by ck 20160809
     * modify by ck 20160914    权限增加
     * modify by ck 20160923    权限细化
     */
    public function appStoreListAction()
    {
        $this->view->pick('app/appStoreList');
        Main::showNavPosition();
        Assets::easyUI('js/app/appStoreList.js');
        Assets::fileInput();
        switch($this->request->getQuery('iAppType', 'int')){                            //检查权限
            case 1: $checkPower = UserPower::checkUserPower('App_AppList_Company'); break;
            case 2: $checkPower = UserPower::checkUserPower('App_AppList_OutSide'); break;
            default: $checkPower = UserPower::checkUserPower('App_AppList');
        }
        $checkPower or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109101001));
        Template::exists('XHApp_Store', 'both') or die(Main::showMessageModal('相关配置文件不存在，请先创建！', 109101002));
        $listButtonArr = $formButtonArr = array();
        if(UserPower::checkUserPower('App_AppList_Add')){                                 //判断是否有添加权限
            $listButtonArr[] = array('plain'=>'true', 'id'=>'bt_list_add', 'text'=>'增加', 'icon'=>'fa-plus');
            $formButtonArr[] = array('id'=>'bt_form_add', 'text'=>'增加', 'class'=>'disabled');
            $this->view->setVar('AddEdit', true);                                       //增加，修改页面显示标识
        }
        if(UserPower::checkUserPower('App_AppList_Edit')){                                //判断是否有修改权限
            $formButtonArr[] = array('id'=>'bt_form_edit', 'text'=>'修改', 'class'=>'disabled');
            $listButtonArr[] = array('id'=>'bt_list_enable', 'text'=>'启用', 'plain'=>'true', 'icon'=>'fa-chain');
            $listButtonArr[] = array('id'=>'bt_list_disable', 'text'=>'禁用', 'plain'=>'true', 'icon'=>'fa-chain-broken');
            $listButtonArr[] = array('id'=>'bt_list_DownEnable', 'text'=>'启用下载', 'plain'=>'true', 'icon'=>'fa-chain');
            $listButtonArr[] = array('id'=>'bt_list_DownDisable', 'text'=>'禁用下载', 'plain'=>'true', 'icon'=>'fa-chain-broken');
            $this->view->setVar('AddEdit', true);
        }
        if(UserPower::checkUserPower('App_AppList_Del')){                                 //判断是否有删除权限
            $listButtonArr[] = array('plain'=>'true', 'id'=>'bt_list_del', 'text'=>'删除', 'icon'=>'fa-trash');
        }
        if(UserPower::checkUserPower('App_AppList_ContactQBank')){                        //判断是否有关联题库权限
            $listButtonArr[] = array('plain'=>'true', 'id'=>'bt_list_ContactBank', 'text'=>'关联题库', 'icon'=>'fa-pencil');
        }
        if(UserPower::checkUserPower('App_AppList_ContactRPack')){
            $listButtonArr[] = array('plain'=>'true', 'id'=>'bt_list_ContactPack', 'text'=>'关联资源包', 'icon'=>'fa-pencil');
        }
        $listButtonArr[] = array('id'=>'bt_list_OpenDownPage', 'text'=>'下载页面', 'plain'=>'true', 'icon'=>'fa-download');
        $formButtonArr[] = array('id' => 'bt_form_back', 'text' => '返回');
        $formButtonArr[] = array('id' => 'bt_form_reset', 'text' => '重置');
        $buttonToolbar = Template::createButtonToolBar($listButtonArr);
        $this->view->setVars(array(
            'List'          => Template::createList('List', 'XHApp_Store', array('buttonToolbar' => $buttonToolbar)),
            'Form'          => Template::createForm('XHApp_Store'),
            'FormButton'    => Template::createButtonToolBar($formButtonArr)
        ));
    }

    /**
     * 获取应用下载页面地址
     *
     * create by ck 20161104
     * modify by ck 20161118    数据库获取信息
     */
    public function getAppDownUrlAction()
    {
        $this->view->disable();
        $url = Main::getConfigByName('appDown');
        $url = $url['url'];
        $url or $url = 'http://appstore.yunzuoye.net/';
        echo $url;
    }

    /**
     * 根据页码及每页行数获取数据并以json格式返回
     *
     * create by ck 20160304
     * modify by ck 20160602
     * modify by ck 20160914    分页方式更改
     */
    public function getAppStoreDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $appType = $this->request->getPost('iAppType', 'int');   //应用类型
        $parameters  = array();
        $parameters['order']        = 'iAppCode';
        $parameters['columns']      = 'iAppId,iAppCode,sAppName,iAppType,bAppApart,bOutSchool,sAppDownUrl,bAppDown,sAppPackage,sAppVersion,iAppSystem,iAppTarget,bAppEnable,bAppHide';
        $parameters['conditions']   = 'bDelete = 0 AND bAppHistory = 0';
        if($appType) $parameters['conditions'] .= " AND iAppType = {$appType}";
        echo Main::runModelPaginator('\\Admin\\Models\\app\\XhappStore', $parameters);
    }

    /**
     * 根据传入信息判断应用包名是否与其他应用重复，重复则报错
     * 检查是否版本相同，相同则提示是否覆盖，如果有覆盖标记则覆盖
     * 版本不同则新增
     *
     * create by ck 20160304
     * modify by ck 20160531    应用编号，包名，系统，版本唯一
     * modify by ck 20160923    去除保存应用，使用文件管理服务器
     */
    public function modifyAppStoreRecordAction(){
        $this->view->disable();
        $this->request->isPost() or die;
        $realData = Main::getRealData($this->request->getPost());
        if(empty($realData['iAppId'])) unset($realData['iAppId']);
        $realData['iAppCode'] && $realData['sAppVersion'] or die(Main::showMessageModal('缺少参数！', 109101029));
        XhappStore::checkPackageName($realData) or die(Main::showMessageModal('检测到包名与其他应用包名重复，操作失败！', 109101003));
        $this->dealAppSavePath($realData);
        $dbRollback = false;
        $this->db->begin();
        $oldApp = XhappStore::getOldApp($realData);
        if($oldApp){
            if($oldApp->sAppVersion != $realData['sAppVersion']){                                           //有记录但版本不同
                self::checkAppOperatePower($realData['iAppType'], true) or die(Main::showMessageModal('无新增权限！', 109101009));
                $oldApp->bAppHistory = 1;
                $oldApp->updateData() or die(Main::showMessageModal('操作失败！', 109101005));
                $app = XhappStore::createRecord(null, $realData, $oldApp);
                if(!$app->updateData()) {                                                      //109101008
                    $dbRollback = true;
                    goto dealTrans;
                }
                if(!$this->insertDroidWallAndRetainByApp($app)){
                    $dbRollback = true;
                    goto dealTrans;
                }
                Main::createCommitLog('app', 'AppStore', 'add', $app, $app->iAppId, '应用版本不同，应用更新');
            }
            else{                                                                                           //有记录且版本相同
                if(isset($realData['Cover']) && $realData['Cover'] == '1'){                                                              //是否确认覆盖
                    self::checkAppOperatePower($realData['iAppType'], false) or die(Main::showMessageModal('无修改权限！', 109101010));
                    $app = XhappStore::createRecord($oldApp->iAppId, $realData);
                    $app->updateData() or die(Main::showMessageModal('操作失败！', 109101006));
                    if(!$this->insertDroidWallAndRetainByApp($app)){
                        $dbRollback = true;
                        goto dealTrans;
                    }
                    Main::createCommitLog('app', 'AppStore', 'edit', $app, $app->iAppId, '应用版本相同，信息覆盖');
                    echo "<script>window.top.xhTop.showModal({content: '覆盖成功！', title: '提示', size: 'sm');</script>";
                }
                else{
                    echo "<script>window.top.xhTop.showModal({content: '检测到该版本已有记录，是否覆盖？', title: '警告', button: '覆盖', size: 'sm'}, window.parent.confirmCover);</script>";
                    die;
                }
            }
        }
        else{
            self::checkAppOperatePower($realData['iAppType'], true) or die(Main::showMessageModal('无新增权限！', 109101011));
            $app = XhappStore::createRecord(null, $realData);
            $app->insertData() or die(Main::showMessageModal('操作失败！', 109101007));
            if(!$this->insertDroidWallAndRetainByApp($app)){
                $dbRollback = true;
                goto dealTrans;
            }
            Main::createCommitLog('app', 'AppStore', 'add', $app, $app->iAppId, '应用不存在，应用新增');
        }
        dealTrans:
        if($dbRollback) {
            $this->db->rollback();
            die(Main::showMessageModal('操作失败！', 109101008));
        }
        $this->db->commit();
        echo '执行成功！';
    }

    /**
     * 根据信息保存文件到指定路径
     *
     * @param $data
     *
     * create by ck 20170121
     */
    function dealAppSavePath($data)
    {
//        $appParseInfo = Main::getConfigByName('appParse');
//        $tempPath = $appParseInfo['tempPath'];
//        $tempPath or $tempPath = '/Mailserver/cache/temp/';
//        $savePath = $appParseInfo['savePath'];
//        $savePath or $savePath = '/Mailserver/cache/XHAppFiles/';
        $savePath = $tempPath = TEMP_PATH . '/';
        $savePath = $savePath . $data['iAppCode'] . '/' . $data['sAppVersion'] . '/';
        is_dir($savePath) or mkdir($savePath, 777, true);
        if(!empty($data['sAppDownUrl'])){
            $fileBaseName = basename($data['sAppDownUrl']);
            if(is_file($tempPath . $fileBaseName)){
                echo '文件转存成功！';
                rename($tempPath . $fileBaseName, $savePath. $fileBaseName);
            }
        }
        if(!empty($data['sAppCoverUrl'])){
            $iconBaseName = basename($data['sAppCoverUrl']);
            if(is_file($tempPath . $iconBaseName)){
                echo '图标转存成功！';
                rename($tempPath . $iconBaseName, $savePath. $iconBaseName);
            }
        }
        if(!empty($data['sPlistUrl'])){
            $plistBaseName = basename($data['sPlistUrl']);
            if(is_file($tempPath . $plistBaseName)){
                echo 'plist转存成功！';
                rename($tempPath . $plistBaseName, $savePath. $plistBaseName);
            }
        }
    }

    /**
     * 插入防火墙及保留应用记录
     *
     * @param $app
     * @return bool
     *
     * create by ck 20161018
     * modify by ck
     */
    function insertDroidWallAndRetainByApp($app)
    {
        if($app->iAppSystem == 1){
            if(!XhappDroidwall::createRecordForNewApp($app->sAppName, $app->sAppPackage)) return false;
            if(!XhappRetain::createRecordForNewApp($app->sAppPackage, $app->sAppName, $app->sAppVersion, $app->iAppType)) return false;
        }
        return true;
    }

    /**
     * 根据应用类型，操作类型判断用户是否有权限操作
     *
     * @param $appType
     * @param bool|true $isNew
     * @return bool
     *
     * create by ck 20160923
     * modify by ck 20170115    添加key判断，通过则直接拥有权限
     */
    function checkAppOperatePower($appType, $isNew = true){
        $key = $this->request->get('key', 'string');
        if($key && $key == strtoupper(md5(date('Ymd') . '+' . $this->config->get('key')))) return true;
        if($isNew){
            switch($appType){
                case 1: return UserPower::checkUserPower('App_AppList_Company_Add');
                case 2: return UserPower::checkUserPower('App_AppList_OutSide_Add');
                default: return UserPower::checkUserPower('App_AppList_Add');
            }
        }
        else{
            switch($appType){
                case 1: return UserPower::checkUserPower('App_AppList_Company_Edit');
                case 2: return UserPower::checkUserPower('App_AppList_OutSide_Edit');
                default: return UserPower::checkUserPower('App_AppList_Edit');
            }
        }
    }

    /**
     * 设置应用状态
     *
     * create by ck 20161020
     */
    public function setAppStateAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        UserPower::checkUserPower('App_AppList_Edit') or die('（109101015）无操作权限！');
        $ids    = $this->request->getPost('ids');
        $target = $this->request->getPost('target');
        switch($target){
            case 'enable':      $sqlParamStr = "bAppEnable = 1"; break;
            case 'disable':     $sqlParamStr = "bAppEnable = 0"; break;
            case 'downEnable':  $sqlParamStr = "bAppDown   = 1"; break;
            case 'downDisable': $sqlParamStr = "bAppDown   = 0"; break;
            default: die('（109101016）无此操作类型');
        }
        $sqlStr = "UPDATE \\Admin\\Models\\app\\XhappStore SET {$sqlParamStr} WHERE iAppId IN ({$ids})";
        $query = $this->modelsManager->executeQuery($sqlStr);
        $query or die('（109101017）操作失败');
        echo '操作成功';
        Main::createCommitLog('app', 'AppStore', $target, ['ids' => $ids, 'type' => $target], null, '批量启用/禁用');
    }

    /**
     * 根据传入id字符串，根据逗号分割后删除记录
     *
     * create by ck 20160304
     * modify by ck 20160616
     */
    public function delDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        UserPower::checkUserPower('App_AppList_Del') or die('（109101014）无删除权限！');
        $idArr = explode(',', $this->request->getPost('ids', 'string'));
        $dbRollback = false;
        $this->db->begin();
        XhappStore::deleteRecordById($idArr) or die('（109101011）删除失败！');
        $appInfoArr = XhappStore::getNameAndPackageAndCodeById($idArr);
        $appNameArr = array_column($appInfoArr, 'sAppName');
        if(!XhappDroidwall::deleteRecordByAppName($appNameArr)){
            $dbRollback = true;
            goto dealTrans;
        }
        $appPackArr = array_column($appInfoArr, 'sAppPackage');
        if(!XhappRetain::deleteRecordByAppPackage($appPackArr)){
            $dbRollback = true;
            goto dealTrans;
        }
        $appCodeArr = array_column($appInfoArr, 'iAppCode');
        if(!XhresQuestionbankcontact::deleteRecordByAppCode($appCodeArr)){
            $dbRollback = true;
            goto dealTrans;
        }
        dealTrans:
        if($dbRollback){
            $this->db->rollback();
            die('（109101023）操作失败！');
        }
        Main::createCommitLog('app', 'AppStore', 'del', array('ids' => $idArr), null, '批量删除');
        $this->db->commit();
        echo '删除成功！';
    }

    /**
     * 异步上传应用文件并解析信息，文件及图标上传文件服务器，以json格式返回信息
     * 用于表单提交，新增/修改应用
     *
     * create by ck 20160922
     * modify by ck 20161110    根据后缀检查类型
     * modify by ck 20161118    保存路径根据数据库配置获取
     * modify by ck 20170409    解析应用流程更改，添加老版本信息，优化输入流程
     */
    public function uploadAppFileAction()
    {
        set_time_limit(0);
        $this->view->disable();
        $this->request->hasFiles() or die;
        $tempPath = $savePath = TEMP_PATH . '/';
//        $appParseInfo = Main::getConfigByName('appParse');
//        $tempPath = $appParseInfo['tempPath'];
//        $tempPath or $tempPath = '/Mailserver/cache/temp/';
//        $savePath = $appParseInfo['savePath'];
//        $savePath or $savePath = '/Mailserver/cache/XHAppFiles/';
        (is_dir($tempPath) || mkdir($tempPath, 0777, true)) or die(json_encode(['error' => "（109101027）路径{$tempPath}创建失败！"]));
        (is_dir($savePath) || mkdir($savePath, 0777, true)) or die(json_encode(['error' => "（109101028）路径{$savePath}创建失败！"]));
        $file = $this->request->getUploadedFiles()[0];
        $fileName = $file->getName();
        $fileSuffix = explode('.', $fileName);
        $fileSuffix = end($fileSuffix);
        in_array($fileSuffix, ['apk', 'ipa']) or die(json_encode(['error' => '（109101012）文件类型不正确！']));
        $fullPath = $tempPath . DIRECTORY_SEPARATOR . $fileName;
        if(!is_writable($tempPath)) {
            echo json_encode(['error' => "路径{$tempPath}无写入权限！"], JSON_UNESCAPED_UNICODE);
            die;
        }
        $file->moveTo($fullPath);
        file_exists($fullPath) or die(json_encode(['error' => '文件不存在，请检查']));
        $result = Main::uploadToFileManageSystem($fullPath, 'app', 'XHSVADAPBUABML');    //上传文件获取下载地址
        if(!$result) {
            @unlink($fullPath);
            die(json_encode(['error' => '文件上传失败！']));
        }
        $appInfo = [
            'sAppMd5'       => strtoupper(md5_file($fullPath)),
            'iAppSize'      => $file->getSize(),
            'sAppDownUrl'   => stripslashes($result)
        ];
        $fullPath = realpath($fullPath);                                                    //得到真实路径
        switch($fileSuffix){
            case 'apk': $appInfo = $this->getApkFileInfo($fullPath, $appInfo); break;
            case 'ipa': $appInfo = $this->getIpaFileInfo($fullPath, $appInfo); break;
            default: die(json_encode(['error' => '文件类型不正确！']));
        }
        if(!is_array($appInfo)){
            echo json_encode(['error' => $appInfo], JSON_UNESCAPED_UNICODE);
            die;
        }
        $oldAppInfo = XhappStore::findFirst([
            'conditions' => 'sAppPackage = :appPackage: AND iAppSystem = :appSystem: AND bDelete = 0 AND bAppHistory = 0',
            'bind'       => ['appPackage' => $appInfo['sAppPackage'], 'appSystem' => $appInfo['iAppSystem']]
        ]);
        if($oldAppInfo){
            $appInfo['iAppCode']    = $oldAppInfo->iAppCode;
            $appInfo['bAppApart']   = $oldAppInfo->bAppApart;
            $appInfo['bOutSchool']  = $oldAppInfo->bOutSchool;
            $appInfo['bAppHide']    = $oldAppInfo->bAppHide;
            $appInfo['iAppType']    = $oldAppInfo->iAppType;
            $appInfo['iAppTarget']  = $oldAppInfo->iAppTarget;
            $appInfo['iUpdateLevel']= 2;
        }
        return $this->response->setJsonContent($appInfo);
    }

    /**
     * 根据apk文件路径上传文件，分析apk信息并返回信息
     *
     * @param $fullPath         --文件相对路径（apk文件）
     * @param array|$appInfo    --应用信息
     * @return string
     *
     * create by ck 20160922
     * modify by ck 20161118
     * modify by ck 20161118    保存路径及aapt路径根据数据库配置获取
     */
    function getApkFileInfo($fullPath, $appInfo){
        //获取保存路径及aapt路径
        $appParseInfo = Main::getConfigByName('appParse');
        $tempPath = $appParseInfo['tempPath'];
        $tempPath or $tempPath = '/Mailserver/cache/temp/';
        $appInfo['iAppSystem']  = 1;
        $fileBaseName = basename($appInfo['sAppDownUrl']);
        $fullPath = realpath($fullPath);                                                    //得到真实路径
        $aaptPath = $appParseInfo['aaptPath'];
        $aaptPath or $aaptPath = '';
        exec("{$aaptPath}aapt dump badging {$fullPath} 2>&1", $arr, $var);                  //执行aapt命令
        if($var !== 0) return 'aapt执行失败' . json_encode($arr);
        $appInfoStr = json_encode($arr, JSON_UNESCAPED_UNICODE);
        preg_match("/package: name='(.*?)'/", $appInfoStr, $package);                       //获取包名
        $appInfo['sAppPackage'] = end($package);
        preg_match("/package: (.*?)versionName='(.*?)'/", $appInfoStr, $package);           //获取版本号
        $appInfo['sAppVersion'] = end($package);
        preg_match("/application: label='(.*?)'/", $appInfoStr, $package);                  //获取名称
        $appInfo['sAppName'] = end($package);
        preg_match_all("/application-icon-([0-9]+):'(.*?)'/", $appInfoStr, $package);       //获取所有图标
        $iconZipPath = @stripslashes(end(end($package)));                                   //获取最大图标目录并去除转义
        $zip = new \ZipArchive;
        if ($zip->open($fullPath) === TRUE) {                                               //中文文件名要使用ANSI编码的文件格式
            $zip->extractTo($tempPath, $iconZipPath);                                       //提取图标
            $zip->close();
            $iconPath = $tempPath. $iconZipPath;
            $result = Main::uploadToFileManageSystem($iconPath, 'appIcon', 'XHSVADAPBUABML');
            $iconZipPath = explode('/', $iconZipPath)[0];                                   //图标所在文件夹
            $iconBaseName = basename($result);
            rename($iconPath, $tempPath . $iconBaseName);                                   //重命名图标
            Tool::delDirAndFile($tempPath . $iconZipPath);                                  //删除图标
            if(!$result) {
                return '图标上传失败';
            }
            $appInfo['sAppCoverUrl'] = $result;
        }
        rename($fullPath, $tempPath . $fileBaseName);
        return $appInfo;
    }

    /**
     * 根据ipa路径上传文件，分析ipa信息并返回
     *
     * @param $fullPath
     * @param array|$appInfo    --应用信息
     * @return string
     * @throws \DOMException
     * @throws \CFPropertyList\IOException
     * @throws \CFPropertyList\PListException
     *
     * create by ck 20161111
     * modify by ck 20161118    保存路径根据数据库配置获取
     */
    function getIpaFileInfo($fullPath, $appInfo){
        //获取保存路径及aapt路径
        $appParseInfo = Main::getConfigByName('appParse');
        $tempPath = $appParseInfo['tempPath'];
        $tempPath or $tempPath = '/Mailserver/cache/temp/';
        $appInfo['iAppSystem']  = 2;
        $fileBaseName = basename($appInfo['sAppDownUrl']);
        $fullPath = realpath($fullPath);                                                    //得到真实路径
        $zip = new \ZipArchive;
        if ($zip->open($fullPath) !== TRUE) return '解压失败！';
        $zipPath = $zip->getNameIndex(1);                                                   //获取压缩包路径
        $plistPath = $zipPath. 'Info.plist';
        $iconPath = $zipPath. 'AppIcon60x60@3x.png';
        $zip->extractTo($tempPath, $plistPath);                                             //解压plist文件
        $zip->extractTo($tempPath, $iconPath);                                              //解压图标
        $iconPath = $tempPath . $iconPath;
        $zip->close();
        $content = file_get_contents($tempPath . $plistPath);
        $plist = new CFPropertyList();
        $plist->parse($content);                                                            //解密plist文件
        $plist = $plist->toArray();
        $appInfo['sAppPackage'] = $plist['CFBundleIdentifier'];
        $appInfo['sAppName']    = $plist['CFBundleName'];
        $appInfo['sAppVersion'] = $plist['CFBundleVersion'];
        //code:CFBundleVersion name:CFBundleShortVersionString
        $result = Main::uploadToFileManageSystem($iconPath, 'appIcon', 'XHSVADAPBUABML');
        $iconBaseName = basename($result);
        rename($iconPath, $tempPath . $iconBaseName);
        Tool::delDirAndFile($tempPath . explode(DIRECTORY_SEPARATOR, $zipPath)[0]);
        if(!$result) return '图标上传失败';
        $appInfo['sAppCoverUrl'] = $result;
        $fileName = explode(DIRECTORY_SEPARATOR, $fullPath);
        $fileName = end($fileName);
        $plistFullPath = $tempPath . $fileName . '.plist';
        $plist = fopen($plistFullPath, 'w');                                                //生成plist文件
        $content = '
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>'.$appInfo['sAppDownUrl'].'</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>'.$appInfo['sAppPackage'].'</string>
                <key>bundle-version</key>
                <string>'.$appInfo['sAppVersion'].'</string>
                <key>kind</key>
                <string>software</string>
                <key>title</key>
                <string>'.$appInfo['sAppName'].'</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>
';
        fwrite($plist, $content);
        fclose($plist);
        $result = Main::uploadToFileManageSystem($plistFullPath, 'plist', 'XHSVADAPBUABML', true);
        $plistBaseName = basename($result);
        rename($plistFullPath, $tempPath . $plistBaseName);
        if(!$result) return 'plist文件上传失败';
        $appInfo['sPlistUrl'] = $result;
        rename($fullPath, $tempPath . $fileBaseName);
        return $appInfo;
    }

    /**
     * 应用管理题库页面（列表）
     *
     * create by ck 20160307
     * modify by ck 20160616
     * modify by ck 20160623    无法连接TCP时不可修改
     * modify by ck 20160913    结构更改
     * modify by ck 20160924    js压缩
     */
    public function appContactQBankAction()
    {
        $this->view->pick('app/appContactQBank');
        Assets::easyUI('js/app/appContactQBank.js');
        UserPower::checkUserPower('App_AppList_ContactQBank') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109103007));
        Template::exists('XHRes_QuestionBank', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109103008));
        $bookConfig = Main::getConfigByName('cBookShelf');
        $transitClient = new TransitClient();
        $transitClient->connect($bookConfig['ip'], $bookConfig['port']) or die(Main::showMessageModal('TCP连接失败！', 109103009));
        $this->view->setVars(array(
            'InList'    => Template::createList('InList', 'XHRes_QuestionBank', array('title' => '已关联题库')),
            'NotList'   => Template::createList('OutList', 'XHRes_QuestionBank', array('title' => '未关联题库')),
        ));
    }

    /**
     * 保留应用列表
     *
     * create by ck 20161018
     */
    public function retainListAction()
    {
        $this->view->pick('app/retainList');
        Main::showNavPosition();
        $this->assets->addJs('assets/jquery/ajaxfileupload.js');
        Assets::easyUI('js/app/retainList.js');
        UserPower::checkUserPower('App_RetainList') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109101016));
        Template::exists('XHApp_Retain', 'both') or die(Main::showMessageModal('相关配置文件不存在，请先创建！', 109101017));
        $listButtonArr = $formButtonArr = array();
        if(UserPower::checkUserPower('App_RetainList_Add')){
            $listButtonArr[] = array('plain'=>'true', 'id'=>'bt_list_add', 'text'=>'导入', 'icon'=>'fa-plus');
            $this->view->setVar('AddEdit', true);
        }
        if(UserPower::checkUserPower('App_RetainList_Edit')){
            $listButtonArr[] = array('plain'=>'true', 'id'=>'bt_list_enable', 'text'=>'启用', 'icon'=>'fa-link');
            $listButtonArr[] = array('plain'=>'true', 'id'=>'bt_list_disable', 'text'=>'禁用', 'icon'=>'fa-unlink');
        }
        $formButtonArr[] = array('id' => 'bt_uploadFile', 'text' => '上传', 'class' => 'btn btn-success');
        $formButtonArr[] = array('id' => 'bt_form_back', 'text' => '返回');
        $buttonToolbar = Template::createButtonToolBar($listButtonArr);
        $this->view->setVars(array(
            'List'          => Template::createList('List', 'XHApp_Retain', [
                'buttonToolbar' => $buttonToolbar
            ]),
            'Form'          => Template::createForm('XHApp_Retain'),
            'FormButton'    => Template::createButtonToolBar($formButtonArr)
        ));
    }

    /**
     * 获取保留应用列表数据
     *
     * create by ck 20161018
     */
    public function getRetainDgDataAction()
    {
        $this->view->disable();
        $parameters['conditions'] = 'bDelete = 0';
        echo Main::runModelPaginator('\\Admin\\Models\\app\\XhappRetain', $parameters);
    }

    /**
     * 上传保留应用文件并导入到保留应用列表中
     *
     * create by ck 20161018
     */
    public function uploadRetainFileAction()
    {
        $this->view->disable();
        $tabletItemNo = $this->request->getPost('tabletItemNo', 'string');
        $tabletItemNo && $this->request->hasFiles() or die;
        $contentArr = [];
        foreach($this->request->getUploadedFiles() as $file){
            $file->getRealType() == 'text/plain' or die(json_encode(['error' => '（109101018）文件类型不正确！']));
            $fileContent = file($file->getTempName());
            foreach($fileContent as $rowNum => $data){
                $data = explode(',', $data);
                $node = [];
                foreach($data as $k => $value){
                    $value = explode(':', $value);
                    $node[$value[0]] = $value[1];
                }
                $contentArr[] = $node;
            }
            break;
        }
        $contentArr or die(json_encode(['error' => '（109101019）无内容！']));
        $result = XhappRetain::importRetainList($tabletItemNo, $contentArr);
        $result or die(json_encode(['error' => '（109101020）导入失败！']));
        echo json_encode($result);
    }

    /**
     * 启用/禁用保留应用
     *
     * create by ck 20161018
     */
    public function setRetainStateAction()
    {
        $this->view->disable();
        $ids    = $this->request->getPost('ids', 'string');
        $target = $this->request->getPost('target', 'string');
        switch($target){
            case 'enable':   $sqlParamStr = "bDisable = 0"; break;
            case 'disable':  $sqlParamStr = "bDisable = 1"; break;
            default: die('（109101021）无此操作类型！');
        }
        $sqlStr = "UPDATE \\Admin\\Models\\app\\XhappRetain SET $sqlParamStr WHERE iARId IN ($ids)";
        $query = $this->modelsManager->executeQuery($sqlStr);
        $query or die('（109101022）操作失败！');
        Main::createCommitLog('app', 'AppRetain', $target, ['ids'=>$ids, 'type'=>$target], null, '批量启用/禁用');
        echo '操作成功！';
    }

    /**
     * 应用与资源包关联页面
     *
     * create by ck 20161220
     */
    public function appContactRPackAction()
    {
        $this->view->pick('app/appContactRPack');
        Assets::easyUI('js/app/appContactRPack.js');
        UserPower::checkUserPower('App_AppList_ContactRPack') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109101025));
        Template::exists('XHRes_ResourcePack', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109101026));
        $this->view->setVars(array(
            'InList'    => Template::createList('InList', 'XHRes_ResourcePack', ['title' => '已关联资源包']),
            'NotList'   => Template::createList('OutList', 'XHRes_ResourcePack', ['title' => '未关联资源包']),
        ));
    }

    /**
     * 防火墙列表页面
     * 根据模板文件，列表配置文件，用户权限显示内容
     *
     * create by ck 20160304
     * modify by ck 20160616    优化
     * modify by ck 20160901    结构更改
     */
    public function droidwallListAction()
    {
        $this->view->pick('app/droidwallList');
        Assets::easyUI('js/app/droidwallList.js');
        Main::showNavPosition();
        UserPower::checkUserPower('App_Droidwall') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109102001));
        Template::exists('XHApp_Droidwall', 'both') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109102002));
        $listButtonArr = $formButtonArr = array();
        if(UserPower::checkUserPower('App_Droidwall_Add')){
            $listButtonArr[] = array('id'=>'bt_list_add', 'text'=>'增加', 'plain'=>'true', 'icon'=>'fa-plus');
            $formButtonArr[] = array('id'=>'bt_form_add', 'text'=>'增加', 'class'=>'disabled');
            $this->view->setVar('AddEdit', true);
        }
        if(UserPower::checkUserPower('App_Droidwall_Edit')){
            $formButtonArr[] = array('id'=>'bt_form_edit', 'text'=>'修改', 'class'=>'disabled');
            $this->view->setVar('AddEdit', true);
        }
        if(UserPower::checkUserPower('App_Droidwall_Del')){
            $listButtonArr[] = array('id'=>'bt_list_del', 'text'=>'删除', 'plain'=>'true', 'icon'=>'fa-trash');
        }
        $formButtonArr[] = array('id'=>'bt_form_back', 'text'=>'返回');
        $formButtonArr[] = array('id'=>'bt_form_reset', 'text'=>'重置');
        $buttonToolbar = Template::createButtonToolBar($listButtonArr);
        $this->view->setVars(array(
            'List'          => Template::createList('List', 'XHApp_Droidwall', array('buttonToolbar' => $buttonToolbar)),
            'Form'          => Template::createForm('XHApp_Droidwall'),
            'FormButton'    => Template::createButtonToolBar($formButtonArr)
        ));
    }

    /**
     * 根据页码及每页行数获取数据并以json格式返回
     *
     * create by ck 20160304
     * modify by ck 20160602
     * modify by ck 20160914    分页方式更改
     */
    public function getDroidwallDataAction()
    {
        $this->view->disable();
        $parameters['conditions'] = 'bDelete = 0';
        echo Main::runModelPaginator('\\Admin\\Models\\app\\XhappDroidwall', $parameters);
    }

    /**
     * 插入，修改数据，如id下有记录，则修改，否则新增
     *
     * create by ck 20160304
     * modify by ck 20160616
     * modify by ck 20160914    更改结构，判断操作权限
     * modify by ck 20160930    修复日志操作属性bug
     */
    public function modifyDroidwallRecordAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $realData = Main::getRealData($this->request->getPost());
        $obj = XhappDroidwall::createRecord($realData);
        if($obj->iDWId){
            UserPower::checkUserPower('App_Droidwall_Edit') or die(Main::showMessageModal('无操作权限', 109102003));
            $obj->updateData() or die(Main::showMessageModal('防火墙修改失败！', 109102004));
            Main::createCommitLog('app', 'Droidwall', 'edit', $obj, $obj->iDWId);
        }
        else{
            UserPower::checkUserPower('App_Droidwall_Add') or die(Main::showMessageModal('无操作权限', 109102007));
            $obj->insertData() or die(Main::showMessageModal('防火墙新增失败！', 109102008));
            Main::createCommitLog('app', 'Droidwall', 'add', $obj, $obj->iDWId);
        }
    }

    /**
     * 根据传入id字符串，根据逗号分割后删除记录
     *
     * create by ck 20160304
     * modify by ck 20160616
     * modify by ck 20160914    权限判断，结构优化
     */
    public function delDroidwallRecordAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        UserPower::checkUserPower('App_Droidwall_Del') or die('（109102005）无操作权限！');
        $ids = $this->request->getPost('ids');
        XhappDroidwall::deleteRecordById($ids) or die('（109102006）删除失败！');
        echo '删除成功！';
        Main::createCommitLog('app', 'Droidwall', 'del', array('ids' => $ids), null, '批量删除');
    }

}

